package com.hnkywl.sts.service.taskdeal;

import com.hnkywl.sts.dao.xsgl.GdDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.entity.xsgl.Gd;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.kcgl.KcgdService;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Jerry on 14-2-7.
 */
@Service
public class DoKhGdqcSync {
    private KhDao khDao;
    private GdDao gdDao;

    @Transactional(readOnly = true)
    public List<Kh> findAllGdkh() {
        String hql = "from Kh where gdsl is not null and sl<>0 and qk=?";
        List<Kh> khList = this.khDao.find(hql, false);
        return khList == null ? new ArrayList<Kh>() : khList;
    }

    @Transactional
    public void doGdqcSync(Kh kh) {
        //(xsd.orderid is not null and xsd.createorgan_id=24) or xsd.orderid is null
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = df.format(new Date());
        String sql = "select nvl(sum(xsmx.sbsl),0) as \"sbsl\" from T_BIZ_XSMX xsmx,T_BIZ_XSD xsd where xsd.yck=0 and xsmx.xsd_id=xsd.id and xsd.deleted!=1 and xsmx.deleted!=1 " +
                " and (xsd.fhfs='transfer') and xsd.date_created between to_date('" + dateStr + " 00:00:00','yyyy-MM-dd hh24:mi:ss') and to_date('" + dateStr + " 23:59:59','yyyy-MM-dd hh24:mi:ss') " +
                " and xsmx.kh_id=:khid";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("khid", kh.getId());
        List<Map> list = this.khDao.createSQLQuery(sql)
                .setProperties(param)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .list();

        //List<Object[]> xssbslList = this.khDao.findBySQL(sql, kh.getId());

        if (list != null && list.size() > 0) {
            Object sbsl = list.get(0).get("sbsl");
            sql = "update T_BIZ_KH set kkdsl=sl-?,gdjs = 0,gdsl = 0,gdslhj=0,gdjshj =0 where id=?";
            this.khDao.executeSQL(sql, sbsl, kh.getId());


            String sqlstr="update T_BIZ_GD set deleted=1 where kh_id=?";
            this.gdDao.executeSQL(sqlstr,kh.getId());
        }
    }


    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setGdDao(GdDao gdDao) {
        this.gdDao = gdDao;
    }
}
